package com.bite.forum.controller;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.config.AppConfig;
import com.bite.forum.model.Message;
import com.bite.forum.model.User;
import com.bite.forum.services.IMessageService;
import com.bite.forum.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.List;

@Slf4j
@Tag(name = "消息模块")
@RestController
@RequestMapping("/message")
public class MessageController {
    // 注入消息服务
    @Resource
    private IMessageService messageService;

    // 注入用户服务
    @Resource
    private IUserService userService;

    // 发送消息
    @Operation(description = "发送消息")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                     @Schema(description = "发送者") @RequestParam("receiveUserId") @NotNull Long receiveUserId,
                     @Schema(description = "消息内容") @RequestParam("content") @NotNull String content) {
        // 获取session
        HttpSession session = request.getSession();
        // 获取用户
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户状态
        if(user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 判断是否给自己发送信息
        if(user.getId().equals(receiveUserId)){
            return AppResult.fail("不能给自己发送信息");
        }

        // 获取接收者
        User receiveUser = userService.selectById(receiveUserId);
        // 判断接收者状态
        if(receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.fail("接收者状态异常");
        }

        // 创建消息
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);

        // 发送消息
        messageService.create(message);

        return AppResult.success();
    }

    // 获取未读消息数量
    @Operation(description = "未读消息")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        // 获取session
        HttpSession session = request.getSession();
        // 获取用户
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 获取未读消息数量
        Integer count = messageService.selectUnreadCount(user.getId());

        return AppResult.success(count);
    }

    @Operation(description = "消息列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);
    }

    @Operation(description = "更新消息状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
            @Schema(description = "消息id") @RequestParam("id") @NotNull Long id) {
        Message message = messageService.selectById(id);
        if(message == null || message.getDeleteState() == 1) {
            log.info(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);
        if(!user.getId().equals(message.getReceiveUserId())) {
            log.info(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(id,(byte) 1);
        return AppResult.success();
    }

    /**
     * 回复消息
     * @param request 请求
     * @param repliedId 被回复消息id
     * @param content 回复内容
     * @return AppResult
     */
    @Operation(description = "回复信息")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
           @Schema(description = "消息id") @RequestParam("repliedId") @NotNull Long repliedId,
            @Schema(description = "回复内容") @RequestParam("content") @NotNull String content) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户状态
        if(user.getState() == 1) {
            log.info(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        Message message = messageService.selectById(repliedId);
        if(message == null || message.getDeleteState() == 1) {
            log.info(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        if(user.getId().equals(message.getPostUserId())) {
            log.info("不能给自己发送信息！");
            return AppResult.fail("不能给自己发送信息！");
        }

        Message newMessage = new Message();
        newMessage.setPostUserId(user.getId());
        newMessage.setReceiveUserId(message.getPostUserId());
        newMessage.setContent(content);

        messageService.reply(repliedId, newMessage);
        return AppResult.success();
    }
}
